<?php

namespace app\controllers;

use Yii;
use app\components\BaseController;
use app\components\Log;
use app\components\Loyalty;
use app\models\Tenant;

class CallbackController extends BaseController
{
    public function actionCustomerSave()
    {
        if (Yii::$app->request->isPost) {
            Log::debug('start callback');
            Log::debug('POST', $_POST);
            // 查询该tenant是否存在
            $appid = Yii::$app->request->post('appid');
            if (empty($appid)) {
                Log::debug('appid不存在');exit;
            }
            $this->setAppid($appid);
            
            $tenant = Tenant::find()->where(['appid' => $appid])->one();
            if (empty($tenant)) {
                Log::debug('tenant不存在');exit;
            }

            // 获取用户信息
            $last_name = Yii::$app->request->post('last_name');
            $mobile = Yii::$app->request->post('mobile');
            $gender = Yii::$app->request->post('gender');
            $email = Yii::$app->request->post('email');
            $openid = Yii::$app->request->post('openid');
            
            // 查询该用户是否存在
            $search_re = Loyalty::customer_search(['mobile' => $mobile]);
            // $this->bp($search_re);
            if ($search_re['status'] == 'error') {
                // 不存在用户新建
                return json_encode(['type' => 'new']);
            } elseif ($search_re['status'] == 'success') {
                // 已存在用户直接更新
                $customer = current($search_re['result']['customers']);
                $data = [
                    'code' => $customer['code'],
                    'mobile' => $mobile,
                    'gender' => $gender,
                    'birthday' => $birthday,
                    'email' => $email,
                    'wechat_openid' => $openid,
                ];
                $save_re = Loyalty::customer_update($data);
                $this->bp($save_re);
            } else {
                Log::debug('customer_search error');
            }
            Log::debug('save_re', $save_re);
            // 更新成功
            Log::debug('end callback');
        }
    }

    public function actionCs()
    {
        // $re = Loyalty::customer_search(['mobile' => '17708130206']);
        // $customer = current($re['result']['customers']);
        // $this->bp($customer);
        return $this->render('cs');
    }
}
